<template>
  <ToolbarButton
    icon="i-ri-file-word-2-line"
    title="导入Word"
    :large-icon="props.largeIcon"
    :hide-text="props.hideText"
    @click="onClick"
  />
  <input
    ref="fileInputRef"
    type="file"
    accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    class="hidden"
    @change="onFileChange"
  />
  <el-dialog v-model="showMessageDialog" title="导入提示" width="420px">
    <div v-if="importMessages.length === 0">已完成导入。</div>
    <ul v-else class="list-disc pl-4">
      <li v-for="(m, idx) in importMessages" :key="idx">{{ m.message }}</li>
    </ul>
    <template #footer>
      <el-button type="primary" size="small" @click="showMessageDialog = false">知道了</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, inject, type Ref } from 'vue'
import type { Editor } from '@tiptap/vue-3'
import ToolbarButton from "../../../button/index.vue";
import { importWordDocument, filterImportMessages } from '../../../../utils/doc/index'

defineOptions({ name: 'ImportWord' })

const props = withDefaults(
  defineProps<{
    largeIcon?: boolean;
    hideText?: boolean;
  }>(),
  {
    largeIcon: false,
    hideText: true,
  }
);

const editor = inject<Ref<Editor | null>>('editor')

const fileInputRef = ref<HTMLInputElement | null>(null)
const showMessageDialog = ref(false)
const importMessages = ref<Array<{ type: string; message: string }>>([])

const onClick = () => {
  fileInputRef.value?.click()
}

const onFileChange = async (e: Event) => {
  const input = e.target as HTMLInputElement
  const file = input.files?.[0]
  input.value = ''
  if (!file) return

  try {
    // 使用工具函数导入Word文档
    const result = await importWordDocument(file, {
      includeEmbeddedStyleMap: true,
      processHtml: true, // 启用HTML后处理
    })
    console.log('----------------导入结果----------------')
    console.log('HTML长度:', result.html?.length)
    console.log('消息数量:', result.messages?.length)
    console.log('HTML预览:', result.html?.substring(0, 200))
    console.log('----------------导入结果----------------')

    // 过滤和处理消息
    const filteredMessages = filterImportMessages(result.messages)
    
    // 如果有错误，显示错误并返回
    const errors = filteredMessages.filter((m: { type: string; message: string }) => m.type === 'error')
    if (errors.length > 0) {
      importMessages.value = errors
      showMessageDialog.value = true
      return
    }

    // 设置过滤后的消息
    importMessages.value = filteredMessages
    // 仅当还有其他提示时才展示对话框
    showMessageDialog.value = filteredMessages.length > 0

    // 将内容设置到编辑器，使用try-catch捕获解析错误
    // 注意：导入时可能会看到浏览器控制台的"touchstart passive"警告
    // 这是来自Tiptap图片resize扩展的性能警告，不影响功能，可以忽略
    try {
      if (editor?.value) {
        editor.value.chain().focus().setContent(result.html).run()
      }
    } catch (parseError: unknown) {
      // 如果解析失败，尝试使用更安全的方式
      console.error('HTML解析错误:', parseError)
      const errorMsg = parseError instanceof Error ? parseError.message : '导入内容解析失败，可能存在不支持的格式'
      
      // 尝试使用更安全的方式清理HTML后再导入
      try {
        // 创建一个更激进的清理函数
        const cleanHtml = (() => {
          const domparser = new DOMParser()
          const doc = domparser.parseFromString(result.html, 'text/html')
          
          // 移除所有可能导致问题的属性和样式
          const allElements = doc.querySelectorAll('*')
          allElements.forEach(el => {
            const htmlEl = el as HTMLElement
            // 只保留最基本的属性
            const allowedAttrs: string[] = []
            if (htmlEl.tagName === 'IMG') {
              allowedAttrs.push('src', 'alt', 'width', 'height')
            } else if (htmlEl.tagName === 'A') {
              allowedAttrs.push('href')
            } else if (htmlEl.tagName === 'TD' || htmlEl.tagName === 'TH') {
              allowedAttrs.push('colspan', 'rowspan')
            } else if (htmlEl.tagName === 'UL' || htmlEl.tagName === 'OL') {
              allowedAttrs.push('type', 'data-type')
            } else if (htmlEl.tagName === 'LI') {
              allowedAttrs.push('data-type', 'data-checked')
            } else if (htmlEl.tagName === 'DIV') {
              allowedAttrs.push('data-type', 'data-page-type', 'data-toc-id')
            }
            
            // 移除不允许的属性
            Array.from(htmlEl.attributes).forEach(attr => {
              if (!allowedAttrs.includes(attr.name.toLowerCase())) {
                htmlEl.removeAttribute(attr.name)
              }
            })
            
            // 移除所有行内样式
            htmlEl.removeAttribute('style')
          })
          
          return doc.body.innerHTML
        })()
        
        if (editor?.value) {
          editor.value.chain().focus().setContent(cleanHtml).run()
          importMessages.value = [{ 
            type: 'warning', 
            message: '部分格式可能已丢失，但内容已成功导入' 
          }]
          showMessageDialog.value = true
        }
      } catch (retryError) {
        importMessages.value = [{ 
          type: 'error', 
          message: errorMsg + '。请检查Word文档格式是否正确。' 
        }]
        showMessageDialog.value = true
      }
    }

  } catch (err: unknown) {
    const errorMessage = err instanceof Error ? err.message : '导入失败，请检查文件格式'
    importMessages.value = [{ type: 'error', message: errorMessage }]
    showMessageDialog.value = true
  }
}
</script>

<style scoped>
.hidden {
  display: none;
}
</style>


